@echo off
setlocal enabledelayedexpansion

REM PPH Services Shutdown Script (English Version)
REM Safely stop all PPH related services

echo ========================================
echo PPH Services Shutdown
echo ========================================
echo.

set "DEPLOY_DIR=%~dp0.."

echo [INFO] Stopping PPH production services...
echo [INFO] Deploy directory: %DEPLOY_DIR%
echo.

REM Check administrator privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [WARNING] Administrator privileges recommended
    echo Some operations may fail without admin rights
    echo.
)

REM Check PM2
pm2 --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [WARNING] PM2 not found
    echo Will attempt manual process cleanup
    goto :manual_cleanup
)

REM Display current status
echo [STEP 1] Current Service Status
echo ========================================

echo [INFO] Current PM2 processes:
pm2 list
echo.

REM Graceful PM2 shutdown
echo [STEP 2] Graceful PM2 Shutdown
echo ========================================

echo [INFO] Stopping PPH services gracefully...

REM Stop specific services
pm2 stop pph-backend >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Backend service stopped
) else (
    echo [INFO] Backend service was not running
)

pm2 stop pph-frontend >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Frontend service stopped
) else (
    echo [INFO] Frontend service was not running
)

pm2 stop pph-management >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Management service stopped
) else (
    echo [INFO] Management service was not running
)

pm2 stop pph-memory-optimizer >nul 2>&1
if %errorlevel% equ 0 (
    echo [OK] Memory optimizer stopped
) else (
    echo [INFO] Memory optimizer was not running
)

REM Stop all PM2 processes
echo [INFO] Stopping all PM2 processes...
pm2 stop all >nul 2>&1
echo [OK] All PM2 processes stopped
echo.

REM Delete PM2 processes
echo [STEP 3] Cleaning PM2 Processes
echo ========================================

echo [INFO] Deleting PM2 process definitions...
pm2 delete pph-backend >nul 2>&1
pm2 delete pph-frontend >nul 2>&1
pm2 delete pph-management >nul 2>&1
pm2 delete pph-memory-optimizer >nul 2>&1
pm2 delete all >nul 2>&1
echo [OK] PM2 processes cleaned
echo.

REM Manual process cleanup
:manual_cleanup
echo [STEP 4] Manual Process Cleanup
echo ========================================

echo [INFO] Checking for remaining processes...

REM Find and terminate Node.js processes (PPH related)
for /f "tokens=2" %%a in ('tasklist /fi "imagename eq node.exe" /fo csv ^| findstr /v "PID"') do (
    set "pid=%%a"
    set "pid=!pid:"=!"
    
    REM Check if process command line contains PPH related paths
    for /f "tokens=*" %%b in ('wmic process where "processid=!pid!" get commandline /value 2^>nul ^| findstr "CommandLine"') do (
        echo %%b | findstr /i "pph\|3010\|3011\|3012" >nul
        if !errorlevel! equ 0 (
            echo [INFO] Terminating PPH-related process: !pid!
            taskkill /f /pid !pid! >nul 2>&1
        )
    )
)
echo.

REM Clean port occupations
echo [STEP 5] Port Cleanup
echo ========================================

echo [INFO] Cleaning port occupations...

REM Clean port 3010
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3010 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3010: %%a
    taskkill /f /pid %%a >nul 2>&1
)

REM Clean port 3011
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3011 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3011: %%a
    taskkill /f /pid %%a >nul 2>&1
)

REM Clean port 3012
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3012 ^| findstr LISTENING') do (
    echo [INFO] Killing process on port 3012: %%a
    taskkill /f /pid %%a >nul 2>&1
)

echo [OK] Port cleanup completed
echo.

REM Verify shutdown status
echo [STEP 6] Verification
echo ========================================

echo [INFO] Verifying shutdown status...

REM Check PM2 status
pm2 --version >nul 2>&1
if %errorlevel% equ 0 (
    echo [INFO] PM2 process list:
    pm2 list
) else (
    echo [INFO] PM2 not available for status check
)

echo.
echo [INFO] Checking port status...

REM Check if ports are still listening
netstat -an | findstr :3010 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [WARNING] Port 3010 still in use
) else (
    echo [OK] Port 3010 is free
)

netstat -an | findstr :3011 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [WARNING] Port 3011 still in use
) else (
    echo [OK] Port 3011 is free
)

netstat -an | findstr :3012 | findstr LISTENING >nul
if %errorlevel% equ 0 (
    echo [WARNING] Port 3012 still in use
) else (
    echo [OK] Port 3012 is free
)
echo.

REM Optional: Complete PM2 reset
echo [STEP 7] Optional PM2 Reset
echo ========================================

set /p "reset_pm2=Do you want to completely reset PM2? (y/N): "
if /i "%reset_pm2%"=="y" (
    echo [INFO] Performing complete PM2 reset...
    pm2 kill >nul 2>&1
    if exist "%USERPROFILE%\.pm2" (
        echo [INFO] Removing PM2 configuration directory...
        rmdir /s /q "%USERPROFILE%\.pm2" >nul 2>&1
    )
    echo [OK] PM2 completely reset
) else (
    echo [INFO] PM2 reset skipped
)
echo.

REM Display final status
echo ========================================
echo SERVICES SHUTDOWN COMPLETED!
echo ========================================
echo.
echo Current Status:
echo - All PPH services have been stopped
echo - Ports 3010, 3011, 3012 should be free
echo - PM2 processes have been cleaned
echo.
echo To restart services:
echo - Run: start-services-en.bat
echo - Or run: deploy-en.bat for full deployment
echo.
echo To check if any processes are still running:
echo - Check PM2: pm2 list
echo - Check ports: netstat -an ^| findstr ":3010\|:3011\|:3012"
echo - Check processes: tasklist ^| findstr node.exe
echo.

pause
